import cv2
import sys


def CatchUsbVideo(window_name, camera_idx, catch_pic_num, path_name):
    cv2.namedWindow(window_name)

    # 采集器
    grabber = cv2.VideoCapture(camera_idx)

    # 分类器
    faceCascade = cv2.CascadeClassifier("model/face/haarcascade_frontalface_alt2.xml")

    # 人脸方框颜色
    facesColor = (0, 255, 0)

    num = 0

    while grabber.isOpened():
        # 读取一帧数据
        ok, frame = grabber.read()
        if not ok:
            break

        # 将当前帧转换成灰度图像
        grey = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)

        # 人脸方框
        faceRects = faceCascade.detectMultiScale(grey, scaleFactor=1.2, minNeighbors=3, minSize=(32, 32))

        # 大于0则检测到人脸
        if len(faceRects) > 0:
            # 单独框出每一张人脸
            for faceRect in faceRects:
                x, y, w, h = faceRect
                # 将当前帧保存为图片
                img_name = '%s/%d.jpg' % (path_name, num)
                print(img_name)
                image = frame[y - 10: y + h + 10, x - 10: x + w + 10]
                cv2.imwrite(img_name, image)
                # 如果超过指定最大保存数量退出循环
                num += 1
                if num > (catch_pic_num):
                    break
                # 绘制人脸方框
                cv2.rectangle(frame, (x - 10, y - 10), (x + w + 10, y + h + 10), facesColor, 2)
                # 显示当前捕捉到了多少人脸图片
                font = cv2.FONT_HERSHEY_SIMPLEX
                cv2.putText(frame, 'num:%d' % (num), (x + 30, y + 30), font, 1, (255, 0, 255), 4)

        if num > (catch_pic_num):
            break

        # 显示图像
        cv2.imshow(window_name, frame)

        # 等待
        c = cv2.waitKey(10)
        # 退出
        if c & 0xFF == ord('q'):
            break

    # 释放
    grabber.release()
    cv2.destroyAllWindows()


if __name__ == '__main__':
    if len(sys.argv) != 3:
        print("Usage:%s camera_id\r\n" % (sys.argv[0]))
        sys.exit(0)

    CatchUsbVideo("Face Data Grabber", int(sys.argv[1]), int(sys.argv[2]), "data/face_cache")
